#pragma once

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>


#define PATH "."
#define FILENAME  "fifo"

#define ERR_EXIT(m) \
do                  \
{                   \
    perror(m);      \
    exit(EXIT_FAILURE); \
} while(0)

class FileOper
{
public:
    FileOper(const std::string &path, const std::string &name)
    : _path(path), _name(name), _fifoname(path + '/' + name), _fd(-1)
    {
    
    }
    ~FileOper()
    {
        if(_fd != -1)
        {
            close(_fd);
            _fd = -1;
        }
        if(unlink(_fifoname.c_str()) == 0)
        {
            std::cout<<"remove success"<<std::endl;
        }
        else 
        {
            ERR_EXIT("unlink");
        }
    }
    void Creat()
    {
        umask(0);
        if(mkfifo(_fifoname.c_str(), 0666) < 0)
        {
            ERR_EXIT("mkfio");
        }
        else 
        {
            std::cout<<"mkfio success"<<std::endl;
        }
    }
    void OpenForRead()
    {
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if(_fd < 0)
        {
            ERR_EXIT("open");
        }
        std::cout<<"open file success"<<std::endl;
    }
    void OpenForWrite()
    {
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if(_fd < 0)
        {
            ERR_EXIT("open");
        }
        std::cout<<"open file success"<<std::endl;
    }
    void Read()
    {
        char buffer[1024];
        while(true)
        {
            ssize_t n = read(_fd, buffer, sizeof(buffer) - 1);
            if(n > 0)
            {
                buffer[n] = '\0';
                std::cout<<"cilent Say ::" <<buffer<<std::endl;
            }
            else if(n == 0)
            {
                std::cout<<"cilent quit! " <<std::endl;
                break;
            }
            else 
            {
                std::cout<<"read error"<<std::endl;
                break;
            }
        }
    }
    void Write()
    {
        std::string message;
        while(true)
        {
            std::cout<<"please enter::"<<std::endl;
            std::getline(std::cin, message);
            write(_fd, message.c_str(),message.size());
        }
    }
    void Close()
    {
        if(_fd > 0)
        {
            close(_fd);
            _fd = -1;
        }
    }
private:
    std::string _fifoname;
    std::string _name;
    std::string _path;
    int _fd;
};